﻿using AutoMapper;
using DailyApp.WebAPI.ApiResponses;
using DailyApp.WebAPI.DataModel;
using DailyApp.WebAPI.DTOs;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore.Storage;
using System.Collections.Generic;
using System.Linq;

namespace DailyApp.WebAPI.Controllers
{
    /// <summary>
    /// 待办事项API
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class WaitController : ControllerBase
    {
        private readonly DailyAppDbContext db;

        private readonly IMapper mapper;


        /// <summary>
        /// 构造函数
        /// </summary>
        public WaitController(DailyAppDbContext _db, IMapper _mapper)
        {
            db = _db;
            mapper = _mapper;
        }


        /// <summary>
        /// 统计待办事项的数量信息
        /// </summary>
        /// <returns>1--统计成功 -99--异常</returns>
        [HttpGet]
        public IActionResult StatWait()
        {
            ApiResponse res = new ApiResponse();

            try
            {
                //取出所有记录
                var listAll = db.WaitInfo.ToList();
                var listFinshed = listAll.Where(t => t.Status == 1).ToList();

                //组装DTO
                StatWaitDTO statWaitDTO = new StatWaitDTO
                {
                    TotalCount = listAll.Count,
                    FinshedCount = listFinshed.Count,
                };

                res.ResultCode = 1;
                res.ResultMsg = "统计待办事项成功";
                res.ResultData = statWaitDTO;
            }
            catch (Exception)
            {

                res.ResultCode = -99;
                res.ResultMsg = "服务器繁忙...";
            }

            return Ok(res);
        }


        /// <summary>
        /// 添加待办事项数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddWaitInfo(WaitInfoDTO waitInfoDTO)
        {
            ApiResponse res = new ApiResponse();

            try
            {
                //WaitInfo waitInfo = new WaitInfo() { Title = waitInfoDTO.Title, Content = waitInfoDTO.Content, Status = waitInfoDTO.Status };
                WaitInfo waitInfo = mapper.Map<WaitInfo>(waitInfoDTO);//使用mapper转换

                db.WaitInfo.Add(waitInfo);
                int result = db.SaveChanges();

                if (result == 1)
                {
                    res.ResultCode = 1;
                    res.ResultMsg = "添加成功";
                }
                else
                {
                    res.ResultCode = -1;
                    res.ResultMsg = "添加失败";
                }
            }
            catch (Exception)
            {

                res.ResultCode = -99;
                res.ResultMsg = "服务器忙...";
            }

            return Ok(res);
        }


        /// <summary>
        /// 通过条件查询待办事项
        /// </summary>
        /// <param name="title">标题(模糊查询)</param>
        /// <param name="status">状态(条件查询，0-待办，1：完成，others：全部)</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult QueryWaitInfo(string? title, int? status)//?表示可空
        {
            var resp = new ApiResponse();

            try
            {
                //查询所有待办事项
                var list = from A in db.WaitInfo
                           select new WaitInfoDTO
                           {
                               WaitId = A.WaitId,
                               Title = A.Title,
                               Content = A.Content,
                               Status = A.Status,
                           };

                //筛选
                if (!string.IsNullOrEmpty(title))
                {
                    list = list.Where(t => t.Title.Contains(title));
                }

                if (status == 1 || status == 0)
                {
                    list = list.Where(t => t.Status == status);
                }

                resp.ResultCode = 1;
                resp.ResultMsg = "查询成功";
                resp.ResultData = list;
            }
            catch (Exception)
            {

                resp.ResultCode = -1;
                resp.ResultMsg = "查询失败";
            }

            return Ok(resp);
        }


        /// <summary>
        /// 获取所有待办的待办事项
        /// </summary>
        /// <returns>1--成功 -1--失败</returns>
        [HttpGet]
        public IActionResult GetWaittingInfo()
        {
            ApiResponse res = new ApiResponse();

            try
            {
                var list = from A in db.WaitInfo
                           where A.Status == 0
                           select new WaitInfoDTO
                           {
                               WaitId = A.WaitId,
                               Title = A.Title,
                               Content = A.Content,
                               Status = A.Status,
                           };

                res.ResultCode = 1;
                res.ResultMsg = "查询成功";
                res.ResultData = list;
            }
            catch (Exception)
            {

                res.ResultCode = -1;
                res.ResultMsg = "查询失败";
            }

            return Ok(res);
        }


        /// <summary>
        /// 修改待办事项的信息
        /// </summary>
        /// <param name="newWaitInfo 前端修改好的数据,但是Id是固定的"></param>
        /// <returns>1--修改成功 -1--失败  -99--异常</returns>
        [HttpPut]
        public IActionResult ModifyWaitInfo(WaitInfoDTO newWaitInfo)
        {
            var resp = new ApiResponse();

            try
            {
                var dbInfo = db.WaitInfo.Find(newWaitInfo.WaitId);//找到该数据
                if (dbInfo != null)
                {
                    //使用映射器时，应将 newWaitInfo 的属性值 复制到现有的 dbInfo 实体，而不是创建新实例。
                    //将 源对象（newWaitInfo）的属性值复制到一个 新创建的 目标对象（WaitInfo 的新实例），并返回该新对象。
                    //dbInfo 现在指向这个新创建的对象，而不是原来的数据库实体对象。
                    //dbInfo = mapper.Map<WaitInfo>(newWaitInfo);//error--将一个新的实例替换掉了原来的实例，这样会让ef误判。

                    //将 源对象（newWaitInfo）的属性值复制到目标对象（dbInfo），并返回目标对象（dbInfo）
                    mapper.Map(newWaitInfo, dbInfo);
                    var count = db.SaveChanges();

                    if (count == 1)
                    {
                        resp.ResultCode = 1;
                        resp.ResultMsg = "修改成功";
                    }
                    else
                    {
                        resp.ResultCode = -1;
                        resp.ResultMsg = "修改失败";
                    }
                }

            }
            catch (Exception)
            {

                resp.ResultCode = -99;
                resp.ResultMsg = "异常";
            }
            return Ok(resp);
        }


        /// <summary>
        /// 删除待办事项
        /// </summary>
        /// <param name="delWaitInfo">待删除的待办事项</param>
        /// <returns>1--成功 -1--失败 0--未查找到该数据 -99--异常</returns>
        [HttpDelete]
        public IActionResult DeleteWaitInfo(int delId)//delete请求一般不能传递整体的参数
        {
            var resp = new ApiResponse();

            try
            {
                //查找这条数据
                var delItem = db.WaitInfo.FirstOrDefault(t => t.WaitId == delId);

                if (delItem != null)
                {
                    db.WaitInfo.Remove(delItem);
                    var count = db.SaveChanges();

                    if (count == 1)
                    {
                        resp.ResultCode = 1;
                        resp.ResultMsg = "Delete Success!";
                    }
                    else
                    {
                        resp.ResultCode = -1;
                        resp.ResultMsg = "Delete Failed!";
                    }
                }

                else
                {
                    resp.ResultCode = 0;
                    resp.ResultMsg = "Research Failed!";
                }

            }
            catch (Exception)
            {

                resp.ResultCode = -99;
                resp.ResultMsg = "Error!";
            }



            return Ok(resp);
        }
    }
}
